import pymysql
from common.handleconfig import conf


class DB:
    def __init__(self):
        # 创建连接对象
        self.conn = pymysql.connect(
            host=conf.get("db", "host"),
            port=conf.getint("db", "port"),
            user=conf.get("db", "user"),
            password=conf.get("db", "pwd"),
            cursorclass=pymysql.cursors.DictCursor,
            charset='utf8'
        )
        # 创建游标
        self.cur = self.conn.cursor()
    

    def find_one(self, sql):
        """获取查询出的第一条数据"""
        # 执行查询语句
        self.conn.commit()
        self.cur.execute(sql)
        data = self.cur.fetchone()
        return data

    def find_all(self, sql):
        """获取查询出的全部数据"""
        self.conn.commit()
        self.cur.execute(sql)
        data = self.cur.fetchall()
        return data

    def close(self):
        """关闭游标，断开连接"""
        self.cur.close()
        self.conn.close()


